package com.agenda.managedbeans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import com.agenda.model.entities.Profissional;
import com.agenda.model.repositories.ProfissionalRepository;

@ManagedBean
public class ProfissionalBean implements AgendaInterface{
	private Profissional profissional = new Profissional();
	private List<Profissional> profissionais;

	@Override
	public void adiciona(ActionEvent event) {
		// TODO Auto-generated method stub
		EntityManager manager = this.getManager();
		ProfissionalRepository repository = new ProfissionalRepository(manager);
		if (this.profissional.getId() == null) {
			repository.adiciona(profissional);
		} else {
			repository.atualiza(profissional);
		}

		this.profissional = new Profissional();
		this.profissionais = null;
	}

	@Override
	public void preparaAlteracao(ActionEvent event) {
		// TODO Auto-generated method stub
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		ProfissionalRepository repository = new ProfissionalRepository(manager);
		this.profissional = repository.procura(id);
	}

	@Override
	public void remove(ActionEvent event) {
		// TODO Auto-generated method stub
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		ProfissionalRepository repository = new ProfissionalRepository(manager);
		this.profissional = repository.procura(id);
		repository.remove(id);
		this.profissionais = null;
	}

	public List<Profissional> getProfissionais() {
		if(this.profissionais == null){
			EntityManager manager = this.getManager();
			ProfissionalRepository repository = new ProfissionalRepository(manager);
			repository.getList();
		}
		
		return profissionais;
	}

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");
	}

	public Profissional getProfissional() {
		return profissional;
	}

	public void setProfissional(Profissional profissional) {
		this.profissional = profissional;
	}

}
